package com.bywlkjs.bygo.wechat.applet.spring.boot.entity;

import com.alibaba.fastjson.JSON;
import com.bywlkjs.bygo.wechat.applet.config.WechatAppletConfig;
import com.bywlkjs.bygo.wechat.applet.entity.AuthCode2SessionEntity;
import com.bywlkjs.common.util.WebSentUtil;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;

@Service
public class AuthGetAccessTokenEntity implements Serializable {

    public static String REQUEST_URL = "https://api.weixin.qq.com/cgi-bin/token";

    @Data
    @Accessors(chain = true)
    public static class Param {
        private String grant_type = "client_credential";
        private String appid;
        private String secret;

        public static Param createInstance(WechatAppletConfig wechatAppletConfig) {
            Param param = new Param();
            param.setAppid(wechatAppletConfig.getAppid());
            param.setSecret(wechatAppletConfig.getSecret());
            return param;
        }

    }

    @Data
    @Accessors(chain = true)
    @Service
    public static class Result {
        private String accessToken;
        private String expiresIn;
        private Integer errcode;
        private String errmsg;

        @Autowired
        private WechatAppletConfig wechatAppletConfig;

        public com.bywlkjs.bygo.wechat.applet.entity.AuthGetAccessTokenEntity.Result analysis(com.bywlkjs.bygo.wechat.applet.entity.AuthGetAccessTokenEntity.Param param){
            param.setAppid(wechatAppletConfig.getAppid()).setSecret(wechatAppletConfig.getSecret());
            String result= WebSentUtil.sendGet(AuthCode2SessionEntity.REQUEST_URL,param);
            return JSON.parseObject(result, com.bywlkjs.bygo.wechat.applet.entity.AuthGetAccessTokenEntity.Result.class);
        }
    }

}
